package com.app114.app.android.rk.webkit;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.view.KeyEvent;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.app114.app.android.rk.log.Logger;

public class ExtendedWebViewClient extends WebViewClient {
	private static final String TAG = ExtendedWebViewClient.class.getSimpleName();
	private WebClientListener mListener;

	public ExtendedWebViewClient(WebClientListener listener) {
		this.mListener = listener;
	}

	@Override
	public void onLoadResource(WebView view, String url) {
		Logger.i(TAG, "onLoadResource-->" + url);
		super.onLoadResource(view, url);
	}

	@Override
	public void onPageFinished(WebView view, String url) {
		Logger.i(TAG, "onPageFinished-->" + url);
		WebviewUtils.setBlockNetworkImage(view, false) ;
		super.onPageFinished(view, url);
	}

	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		Logger.i(TAG, "onPageStarted-->" + url);
		WebviewUtils.setBlockNetworkImage(view, true) ;
		super.onPageStarted(view, url, favicon);
	}

	@Override
	public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
		Logger.i(TAG, "onReceivedError-->" + failingUrl + ",errorCode-->" + errorCode);
		super.onReceivedError(view, errorCode, description, failingUrl);
	}

	@Override
	public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
		Logger.i(TAG, "onReceivedHttpAuthRequest-->" + host + ",realm-->" + realm);
		super.onReceivedHttpAuthRequest(view, handler, host, realm);
	}

	@Override
	public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
		Logger.i(TAG, "onReceivedSslError-->");
		super.onReceivedSslError(view, handler, error);
	}

	@Override
	public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
		Logger.i(TAG, "onUnhandledKeyEvent-->" + event.getKeyCode());
		super.onUnhandledKeyEvent(view, event);
	}

	@Override
	public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
		Logger.i(TAG, "shouldOverrideKeyEvent-->" + event.getKeyCode());
		return super.shouldOverrideKeyEvent(view, event);
	}
	
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// if (url.startsWith(mWeibo.getRedirectUrl())) {
		// handleRedirectUrl(view, url);
		// WeiboDialog.this.dismiss();
		// return true;
		// }
		return mListener.shouldOverrideUrlLoading(view, url);
		// launch non-dialog URLs in a full browser
		// mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
	}

	public interface WebClientListener {
		boolean shouldOverrideUrlLoading(WebView view, String url);
	}

}
